$(document).ready(function() {

    var ctx = $("#ctx").val(); //获取服务器地址

    /***************************    创意列表页    ***************************/

    $("#btn-create").click(function() {
        if ($("#adGroupId").val() == "" || $("#adGroupId").val() == -1) {
            $(this).attr("href", "javascript:void(0);");
            bootbox.alert("请选择投放！");
            $(this).attr("title", "请选择投放");
            return false;
        }
    });

    $('ul#adGroupul_son_ul li').live("click", function() {
        $("#myform").attr("action", ctx + "/advertiser/main/ad/target/ad/list?adGroupId=" + $("#adGroupId").val() + "&orderId=" + $("#orderId").val() + "&advertiserId=" + $("#advertiserId").val());
        refreshData();
    });

    //状态全部、开启、停用
    if ($("#status").val() == 2 || $("#status").val() == "") {
        $("#selectBar_status a:first").addClass("selectBar_change");
    }
    $("#selectBar_status a").each(function() {
        var value = $(this).attr("value");
        if ($("#status").val() == value) {
            $(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
        }
    });
    $("#selectBar_status a").click(function() {
        $("#status").val($(this).attr("value"));
        refreshData();
    });

    //开启,暂停
    $("#btn-enable,#btn-disable,#btn-delete").click(function() {
        if ($(this).attr("id") == "btn-enable") {
            url = ctx + "/advertiser/main/ad/target/ad/enable";
        } else if ($(this).attr("id") == "btn-disable") {
            url = ctx + "/advertiser/main/ad/target/ad/disable";
        } else if ($(this).attr("id") == "btn-delete") {
            url = ctx + "/advertiser/main/ad/target/ad/delete";
        }
        singleOper($(this), url);
    });

    //批量开启,批量暂停
    $("#all-btn-enable,#all-btn-disable,#all-btn-delete").click(function() {
        if ($(this).attr("id") == "all-btn-enable") {
            url = ctx + "/advertiser/main/ad/target/ad/enable";
        } else if ($(this).attr("id") == "all-btn-disable") {
            url = ctx + "/advertiser/main/ad/target/ad/disable";
        } else if ($(this).attr("id") == "all-btn-delete") {
            url = ctx + "/advertiser/main/ad/target/ad/delete";
        }
        batchOpear($(this), url);
    });

    /***************************    创建，编辑创意    ***************************/

    //批量上传
    if ($("#all-btn-upload").html()) {
        $('#all-input-file').fileupload({
            autoUpload: true,
            url: ctx + '/advertiser/main/ad/target/create-banner/upload?adGroupId=' + $("#adGroupId").val(),
            done: function(e, data) {
                bootbox.alert(data.result, function(ensure) {
                    refreshData();
                });
            }
        });
    }

    $('#all-btn-upload').click(function() {
        $('#all-input-file').click();
    });

    //编辑
    if ($("#input-file-div").html()) {
        $('#input-file').fileupload({
            autoUpload: true,
            url: ctx + '/advertiser/main/ad/target/ad/upload?bannerId=' + $("#bannerId").val(),
            done: function(e, data) {
                var path = data.result;
                if (path.indexOf("~") < 0) {
                    var file_name = path.split("--")[path.split("--").length - 1];
                    var file_path = path.split("--")[path.split("--").length - 2];
                    //alert(file_name);
                    //alert(file_path);
                    $("#bannerTemplateName").val(file_name);
                    $("#bannerTemplateName1").val(file_name);
                    $("#upload-path").val(file_path);
                } else {
                    alert(path);
                }
            }
        });
    }

    $("#upload-click").click(function() {
        $("#input-file").click();
    });

    //批量删除创意
    $("#btn-delete-create").click(function() {
        batchOpear($(this), ctx + "/advertiser/main/ad/target/create-banner/delete");
    });

    //初始校验表单
    if ($("#validateForm").html()) {
        $("#validateForm").autovalidate();
    }

    $(".btn-save").click(function() {
        if (!$("#validateForm").validate()) {
            return false;
        }
        $("#validateForm").submit();
        return false;
    });

    $(".btn-cancel").click(function() {
        window.location.href = ctx + "/advertiser/main/ad/target/ad/list?adGroupId=" + $("#adGroupId").val() + "&orderId=" + $("#orderId").val() + "&advertiserId=" + $("#advertiserId").val();
    });

    /***************************    从创意中心选择    ***************************/
    //获取创意尺寸
    if ($("#size").val() == 0 || $("#size").val() == "") {
        $("#selectBar_size a:first").addClass("selectBar_change");
    }
    $("#selectBar_size a").each(function() {
        var value = $(this).attr("value");
        if ($("#size").val() == value) {
            $(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
        }
    });
    $("#selectBar_size a").click(function() {
        $("#size").val($(this).attr("value"));
        if ($(this).attr("value") != "") {
            var _size = $(this).attr("value").split('x', 2);
            $("#width").val(_size[0]);
            $("#height").val(_size[1]);
        } else {
            $("#width").val("");
            $("#height").val("");
        }
        refreshData();
    });

    //创意类型
    if ($("#type").val() == 0 || $("#type").val() == "") {
        $("#selectBar_type a:first").addClass("selectBar_change");
    }
    $("#selectBar_type a").each(function() {
        var value = $(this).attr("value");
        if ($("#type").val() == value) {
            $(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
        }
    });
    $("#selectBar_type a").click(function() {
        $("#type").val($(this).attr("value"));
        refreshData();
    });
    var str = "<label class=\"input-label\"><span class=\"lbl-yes\">*</span>曝光代码</label>" + "<input class=\"input-text\" tabindex=\"1\" id=\"name\" name=\"name\" type=\"text\" value=\"\" readOnly=true>" + "<br/>" + "<label class=\"input-label\"><span class=\"lbl-yes\">*</span>检测代码</label>" + "<input class=\"input-text\" tabindex=\"1\" id=\"name\" name=\"name\" type=\"text\" value=\"\" readOnly=true>";
    $("#official").live("click", function() {
        layer.open({
            type: 2,
            title: '曝光代码监控获取',
            shadeClose: false,
            shade: 0.6,
            fix: false,
            area: ['1360px', '610px'],
            content: ctx + "/advertiser/main/ad/target/official/officials?bannerId=" + $(this).attr("bannerId") + "&bannerTemplateId=" + $(this).attr("bannerTemplateId")
        });
    });

    //加号效果
    $(".red").css({
        color: "red",
        cursor: "pointer",
        fontSize: "20px",
        fontWeight: "bold"
    });
    $(".two").css("display", "none");
    $(".two").each(function() {
        if ($(this).find(".input-text").val() != "") {
            var index = $(this).index(".two");
            $(".red").eq(index).css("display", "none");
            $(this).css("display", "block");
        }
    });

    $(".red").click(function() {
        var index = $(this).index(".red");
        $(".two").eq(index).css("display", "block");
        $(this).css("display", "none");
    })
});

function exportExcel_list() {
    var searchValue = $("#searchValue").val();
    if (searchValue == "请输入关键字") {
        searchValue = "";
    }
    var param = "?adGroupId=" + $("#adGroupId").val() + "&orderId=" + $("#orderId").val() + "&advertiserId=" + $("#advertiserId").val() + "&selectedStatus=" + $("#status").val() + "&searchValue=" + searchValue;
    $("#exportExcel").attr("href", $("#ctx").val() + "/advertiser/main/ad/target/ad/exportAdExcel" + param);
    return false;
}

function createSaveBanner() {
    var trObjs = $("#myform table tbody tr");
    var arr = [];
    trObjs.each(function() {
        var obj = $(this);
        var data = {};
        data["id"] = obj.find(".tdData input[name='id']").val();
        data["name"] = obj.find(".tdName input[name='name']").val();
        data["visitAddress"] = obj.find(".tdData input[name='visitAddress']").val();
        data["clickAddress"] = obj.find(".tdData input[name='clickAddress']").val();
        data["clickAddress2"] = obj.find(".tdData input[name='clickAddress2']").val();
        data["clickAddress3"] = obj.find(".tdData input[name='clickAddress3']").val();
        data["impressionAddress"] = obj.find(".tdData input[name='impressionAddress']").val();
        data["impressionAddress2"] = obj.find(".tdData input[name='impressionAddress2']").val();
        data["impressionAddress3"] = obj.find(".tdData input[name='impressionAddress3']").val();
        //原生信息
        data["displayTitle"] = obj.find(".tdData input[name='displayTitle']").val();
        data["displayText"] = obj.find(".tdData input[name='displayText']").val();
        arr.push(data);
    });
    var jsonUserInfo = JSON.stringify(arr);
    $("#bannerObjs").val(jsonUserInfo);
    $.post($("#ctx").val() + "/advertiser/main/ad/target/create-banner/save", {
        adGroupId: $("#adGroupId").val(),
        bannerObjs: $("#bannerObjs").val()
    }, function(data) {
        window.location.href = $("#ctx").val() + "/advertiser/main/ad/target/ad/list?adGroupId=" + $("#adGroupId").val() + "&orderId=" + $("#orderId").val() + "&advertiserId=" + $("#advertiserId").val();
    });
    return false;
}

function cloneSaveBanner() {
    var checkboxs = $("table tbody .checkboxStyle_change");
    var ids = [];
    checkboxs.each(function() {
        var id = parseInt($(this).attr("id"));
        ids.push(id);
    });
    $.ajax({
        async: false,
        traditional: true,
        type: "POST",
        url: $("#ctx").val() + "/advertiser/main/ad/target/clone-banner/save",
        data: {
            "adGroupId": $("#adGroupId").val(),
            "id": ids
        },
        success: function(data) {
            window.location.href = $("#ctx").val() + "/advertiser/main/ad/target/create-banner/list?adGroupId=" + $("#adGroupId").val();
        }
    });
    return false;
}

//序列化对象
$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    var vCount = 0;
    // 计算json内部的数组最大长度
    for (var item in o) {
        var tmp = $.isArray(o[item]) ? o[item].length : 1;
        vCount = (tmp > vCount) ? tmp : vCount;
    }

    if (vCount > 1) {
        var jsonData2 = [];
        for (var i = 0; i < vCount; i++) {
            var jsonObj = {};
            for (var item in o) {
                jsonObj[item] = o[item][i];
            }
            jsonData2.push(jsonObj);
        }
        return JSON.stringify(jsonData2);
    } else {
        return "[" + JSON.stringify(o) + "]";
    }
};